﻿using MapleLeaf.Pay.Pay;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace MapleLeaf.Client.Injector {

    public class HongshPayClientInjector : HongshPayClientPlugin {

        public override HongshPayClientPluginConfig Config { get; }


        public override object View { get; }

        public override void Start() {
            if (CLRHostingTask == null) {
                string[] argv = Regex.Split(_Config.InitParameter, "->");
                CLRHostingTask = new Task(delegate () {
                    while (CLRHostingTask != null) {
                        try {
                            CLRInjector.Inject(_Config.TargetPath, argv[0], argv[1], argv[2], (argv.Length > 3) ? argv[3] : null);
                        }
                        catch {
                        }
                        Thread.Sleep(3000);
                    }
                });
                CLRHostingTask.Start();
            }
            Config.IsRunning = true;
        }

        public override void Stop() {
            if (CLRHostingTask != null) {
                Task clrhostingTask = CLRHostingTask;
                CLRHostingTask = null;
                clrhostingTask.Wait();
            }
            Config.IsRunning = false;
        }


        public HongshPayClientInjector(HongshPayClientContext ctx) : base(ctx) {

            Config = _Config;
            View = new ConfigView(_Config);
            if (Config.IsRunning) {
                Start();
            }
        }


        static HongshPayClientInjector() {

            _Config = new HongshPayClientInjectorConfig();
        }


        private static readonly HongshPayClientInjectorConfig _Config;

   
        private Task CLRHostingTask;
    }
}
